package com.sinosoft.workflow.biz.service.impl;

import java.util.Map;

import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinosoft.workflow.biz.dao.FlowWorkDao;
import com.sinosoft.workflow.biz.entity.FlowWork;
import com.sinosoft.workflow.biz.service.ExecutionWorkFlowFacadeService;
import com.sinosoft.workflow.exception.WorkFlowException;

/**
 * 
 * 【工作流service接口实现】
 * @author chihouliang
 * @date 2016年8月19日 上午11:20:06 
 * @version V1.0
 */
@Service
public class ExecutionWorkFlowFacadeServiceImpl implements ExecutionWorkFlowFacadeService {

    /**流程引擎*/
    @Autowired
    private ProcessEngine processEngine;
    /**自定义工作流*/
    @Autowired
    private FlowWorkDao flowWorkDao;
    
   /*
    * 启动工作流
    */
    @Override
    public void start(String cBizNo, String cFlowCode, Map<String, Object> cPara) throws WorkFlowException, Exception{
        Integer tFlowCode = Integer.parseInt(cFlowCode);
        //启动一条流程引擎
        ProcessInstance tProcessInstance = processEngine.getExecutionService().startProcessInstanceByKey(cBizNo,cPara);
        //流程引擎id
        String tProcessInstanceId = tProcessInstance.getId();
       
        FlowWork tFlowWork = new FlowWork();
        tFlowWork.setBizNo(cBizNo);
        tFlowWork.setFlowCode(tFlowCode);
        tFlowWork.setProcessInstanceId(tProcessInstanceId);
        //保存到业务表
        flowWorkDao.save(tFlowWork);
    }

    /*
     * 执行工作流
     */
    @Override
    public void signal(String cBizNo, String cFlowCode, Map<String, Object> cVariableMap) throws WorkFlowException ,Exception{
        Integer tFlowCode = Integer.parseInt(cFlowCode);
        //获取流程实例id
        String tProcessId = flowWorkDao.query(cBizNo, tFlowCode);
        //获取TaskService
        TaskService tTaskService = processEngine.getTaskService();
        //获取任务id
        String tTaskId = tTaskService.createTaskQuery().executionId(tProcessId).uniqueResult().getId();
        processEngine.getTaskService().completeTask(tTaskId);
    }

}
